package org.btik.lightweb.interceptor;

import com.google.gson.Gson;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.btik.light.server.platform.common.api.bean.common.ResultFactory;
import org.btik.light.server.platform.common.api.bean.common.StatusResult;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;

import static org.btik.lightweb.interceptor.UserLoginInterceptor.checkUserLoginAnd;

/**
 * @author lustre
 * @since 2023/6/17 18:32
 */
public class PermissionInterceptor implements HandlerInterceptor {

    private final HashSet<String> adminPermission;


    private final byte[] noPermissions;


    public PermissionInterceptor(HashSet<String> adminPermission) {
        Gson gson = new Gson();
        this.adminPermission = adminPermission;
        StatusResult<Object> noPermissions = ResultFactory.failed("NO_PERMISSIONS");
        this.noPermissions = gson.toJson(noPermissions).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return checkUserLoginAnd(request, response, (loginUser) -> {

            String requestURI = request.getRequestURI();
            if (adminPermission.contains(requestURI) && !loginUser.isAdmin()) {
                try {
                    notAdmin(response);
                    return false;
                } catch (IOException e) {
                    return false;
                }

            }
            return true;
        });
    }

    private void notAdmin(HttpServletResponse response) throws IOException {

        response.setContentType("application/json");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(noPermissions);
        outputStream.flush();
    }

}
